
class ConfigController < ApplicationController

	OK = '<span class="ok">OK</span>'

	# ==========
	# Render methods
	# ==========

	def index
		confNames = ['nfSignIn', 'nfPassword', 'PollInterval', 'Path', 'Bitrate', 'BitrateCustom', 'DiskLimit', 'Port', 'ShowThumbs', 'Logging']

		# Required view variables
		@pollOpts = [['half-hour', 30], ['hour', 60], ['4 hours', 240], ['8 hours', 480], ['24 hours', 1440]]

		# Populate view variables
		@title = 'Configuration'

		@post = {}

		def @post.method_missing(symbol) self[symbol.id2name]; end

		confNames.each {|confName|
			@post[confName] = Conf[confName]
		}

		# Compute status displays
		pass = @post.nfPassword
		@hasPassword = !(pass.nil? or pass.empty?)
		@loginStatus = try_login
		@pathStatus = try_path
		@portDefault = Conf::DEFAULT_PORT
	end

	# Show app log
	def log
		if File.exist?(Conf::LOG_PATH)
			headers['Content-Type'] = 'text/plain; charset=utf-8'
			headers['Content-Disposition'] = 'inline; filename="netfluxd.log"'
			render :file => Conf::LOG_PATH
		else
			render :text => '<html><head><title>Netflux Log</title></head><body>No log found</body></html>'
		end
	end

	# ==========
	# AJAX methods
	# ==========

	# Update a config
	def update
		@conf = params[:element_id]
		Conf[@conf] = params[:update_value]
		render :text => Conf[@conf]
	end

protected
	def test_login
		render :text => try_login
	end

	def test_path
		render :text => try_path
	end

	def try_login
		user	= Conf.nfSignIn
		pass	= Conf.nfPassword

		if user.nil? or user.empty? or pass.nil? or pass.empty?

			return 'not configured'
		end

		NetflixClient.new.login ? OK : 'login failed'
	end

	def try_path
		path = Conf.Path

		if not path or path.empty?
			return 'not configured'
		elsif not FileTest.exists?(path)
			return 'does not exist'
		elsif not FileTest.directory?(path)
			return 'not a directory'
		elsif not FileTest.writable?(path)
			return 'not writable'
		end

		OK
	end

end
